<template>
  <el-dialog
    title="分配权限"
    :visible="showPermDialog"
    @close="handleCloseThis"
  >
    <!-- 权限是一颗树 -->
    <!-- 将数据绑定到组件上 -->
    <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
    <!-- id作为唯一标识 -->
    <!-- /*
        ! default-checked-keys 默认勾选数组
        ! 没有双向绑定，手动使用 setCheckedKeys 和 getCheckedKeys 方法进行操作
    */  -->
    <el-tree
      ref="permTree"
      :data="permData"
      :props="{label: 'name'}"
      :show-checkbox="true"
      :check-strictly="true"
      :default-expand-all="true"
      node-key="id"
    />
    <!-- 确定 取消 -->
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="handleAssign"
          >确定</el-button
        >
        <el-button size="small" @click="handleCloseThis">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop, Emit } from 'vue-property-decorator'
import { formatTree } from '@/utils/tree'
import { assignRoleAPI } from '@/api/settings'
import { getPermissionListAPI } from '@/api/permission'
import { getUserRolesAPI } from '@/api/roles'
import { Tree as ElTree } from 'element-ui'

@Component({})
export default class extends Vue {
  @Prop({ default: false }) showPermDialog!: boolean
  @Prop({ default: '' }) roleId!: string // 用来记录分配角色的id

  permData: Array<any> = [] // 专门用来接收权限数据 树形数据

  // id变化时重新获取权限
  @Watch('roleId')
  onIdChange() {
    this.getUserRolesFn()
  }

  created() {
    this.getPermissionListFn()
  }

  async getPermissionListFn() {
    const res = await getPermissionListAPI()
    const list = res.filter((item: any) => item.enVisible === '1')
    this.permData = formatTree(list, '0')
  }

  async getUserRolesFn() {
    /*
      ? 今日一坑
      ? 直接 this.selectCheck = [] 无法清空树形的选中数据
    */
    const { permIds } = await getUserRolesAPI(this.roleId)
    if (this.$refs.permTree) { (this.$refs.permTree as ElTree).setCheckedKeys(permIds) }
    // this.selectCheck = (await getUserRolesAPI(this.roleId)).permIds
  }

  // 关闭弹层
  @Emit('update:showPermDialog')
  handleCloseThis() {
    return false
  }

  // 提交
  async handleAssign() {
    try {
      const newCheck = (this.$refs.permTree as ElTree).getCheckedKeys()
      await assignRoleAPI({ id: this.roleId, permIds: newCheck })
      this.$message.success('操作成功')
      this.handleCloseThis()
    } catch (e) {
      this.$message.info(e)
    }
  }
}
</script>
